#write in 2019,6,2
#write by lizhuoying
import random

from sqlalchemy import create_engine,Column,Integer,String,func

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker


DB_URI='mysql+pymysql://root@127.0.0.1:3306/test?charset=utf8'

engine=create_engine(DB_URI)

Base=declarative_base(engine)#元类编程，将对象转化成元类

class Book(Base):
    __tablename__='person'
    id=Column(Integer,primary_key=True,autoincrement=True)
    name=Column(String(20))
    price=Column(Integer)

    def __repr__(self):
        return '<Book name:%s>'%self.name

Base.metadata.drop_all()
Base.metadata.create_all()

session=sessionmaker(engine)()
for i in range(5):
    book=Book(name='name%d'%i, price=random.randint(50,200))
    session.add(book)

session.commit()
result=session.query(Book.id,Book.name)

print(result)